package com.mxpio.erp.oa.controller;

import com.mxpio.erp.common.enums.OaEnums;
import com.mxpio.erp.common.oa.entity.OaReimbursement;
import com.mxpio.erp.common.oa.entity.OaReimbursementLine;
import com.mxpio.erp.common.oa.service.OaReimbursementLineService;
import com.mxpio.erp.common.oa.service.OaReimbursementService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.security.entity.Dept;
import com.mxpioframework.security.service.DeptService;
import com.mxpioframework.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@Tag(name = "OaReimbursementController", description = "报销单")
@RestController
@RequestMapping("/erp/oa/reim/")
public class OaReimbursementController {

    @Autowired
    private OaReimbursementService oaReimbursementService;

    @Autowired
    private OaReimbursementLineService oaReimbursementLineService;
    @Autowired
    private DeptService deptService;

    @GetMapping("list")
    @Operation(summary = "报销单列表", description = "报销单列表（无分页）", method = "GET")
    public Result<List<OaReimbursement>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<OaReimbursement> list = oaReimbursementService.list(OaReimbursement.class, criteria);
        return Result.OK(list);
    }

    @GetMapping("page")
    @Operation(summary = "报销单列表", description = "报销单列表（分页）", method = "GET")
    public Result<Page<OaReimbursement>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<OaReimbursement> pageResult = oaReimbursementService.listPage(OaReimbursement.class, page, criteria);
        return Result.OK(pageResult);
    }

    @GetMapping("list/{bizNo}")
    @Operation(summary = "根据ID获取报销单", description = "根据ID获取报销单", method = "GET")
    public Result<OaReimbursement> getById(@PathVariable(name = "bizNo", required = true) String bizNo) {
        OaReimbursement reimbursement = oaReimbursementService.getById(OaReimbursement.class, bizNo);
        return Result.OK(reimbursement);
    }

    @RequestMapping("add")
    @Operation(summary = "保存报销表", description = "保存报销表")
    public Result<OaReimbursement> add(@RequestBody OaReimbursement reimbursement) {
        return  oaReimbursementService.saveall(reimbursement);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑", description = "编辑", method = "PUT")
    public Result<OaReimbursement> edit(@RequestBody OaReimbursement reimbursement) {
        OaReimbursement byId = oaReimbursementService.getById(OaReimbursement.class,reimbursement.getBizNo());
        if (!byId.getOrderStatus().equals(OaEnums.OrderStatus.NEW.getCode())){
            return Result.error("在新增状态下才可修改");
        }
        if (!StringUtils.equals(byId.getApplyUserDeptId(),reimbursement.getApplyUserDeptId())){
            Dept levelOneDept = deptService.getLevelOneDept(reimbursement.getApplyUserDeptId());
            if (levelOneDept != null) {
                reimbursement.setOrgDesc(StringUtils.isNotBlank(levelOneDept.getDeptDesc())?levelOneDept.getDeptDesc():levelOneDept.getDeptName());
            }
        }
        //因为前台传输的是全量数据，所以将子表明细删除后，在存储
        List<OaReimbursementLine> oaReimbursementLines = reimbursement.getOaReimbursementLines();
        oaReimbursementLineService.deleteBatch(OaReimbursementLine.class,Criteria.create().addCriterion("bizNo",Operator.EQ,reimbursement.getBizNo()));
        for (OaReimbursementLine line : oaReimbursementLines){
            line.setBizNo(reimbursement.getBizNo());
            oaReimbursementLineService.save(line);
        }
//        oaReimbursementService.save(reimbursement, new SmartCrudPolicyAdapter(){
//            @Override
//            public boolean beforeInsert(CrudContext context){
//                Object o = context.getEntity();
//                if (o instanceof OaReimbursementLine){
//                    OaReimbursement info = context.getParent();
//                    ((OaReimbursementLine) o).setBizNo(info.getBizNo());
//                }
//                return  true;
//            }
//        });
        oaReimbursementService.update(reimbursement);
        return Result.OK(reimbursement);
    }

    @DeleteMapping("remove/{bizNos}")
    @Operation(summary = "根据id删除单子", description = "删除单子,多个id用英文逗号分隔", method = "DELETE")
    public Result<OaReimbursement> remove(@PathVariable(name = "bizNos", required = true) String bizNos) {
        String[] id = bizNos.split(",");
        for(String key : id){
            oaReimbursementService.delete(OaReimbursement.class, key);
            List<OaReimbursementLine> lines = oaReimbursementLineService.list(OaReimbursementLine.class, Criteria.create().addCriterion("bizNo", Operator.EQ, key));
            for (OaReimbursementLine line : lines){
                oaReimbursementLineService.delete(OaReimbursementLine.class, line.getId());
            }
        }
        return Result.OK();
    }

    /**
     * 编辑审批状态
     * @param reimbursement
     * @return
     */
    @PutMapping("edit/bpmn/")
    @Operation(summary = "编辑审批状态", description = "编辑审批状态", method = "PUT")
    public Result<OaReimbursement> editBpmn(@RequestBody OaReimbursement reimbursement) {
        oaReimbursementService.update(reimbursement);
        return Result.OK(reimbursement);
    }

    /**
     * 普通发票
     * @param key
     * @param businessKey
     * @param properties
     * @return
     */
    @RequestMapping("submit/{key}")
    @Operation(summary = "提交申请-工作流",description = "提交申请-工作流")
    public Result<?> change(@PathVariable(name = "key") String key,
                            @RequestParam(value="businessKey", required = false) String businessKey,
                            @RequestBody Map<String, Object> properties) {
        return oaReimbursementService.submit(key, SecurityUtils.getLoginUsername(), businessKey, properties);
    }

    /**
     * 普通发票
     * @param reimbursement
     * @return
     */
    @RequestMapping("submit/Ok")
    @Operation(summary = "提交申请-工作流审核",description = "提交申请-工作流审核")
    public Result<?> submitOK(@RequestBody OaReimbursement reimbursement) {
        return oaReimbursementService.submitOK(reimbursement);
    }

}
